<template>
	<view class="smart-parse-container">
		<view class="content">
			<!-- 订单信息显示 -->
			<view v-if="selectedOrder && selectedOrder.orderNo" class="order-info-section">
				<view class="order-info">
					<text class="order-label">订单号：</text>
					<text class="order-no">{{ selectedOrder.orderNo }}</text>
				</view>
			</view>
			<!-- 输入区域 -->
			<view class="input-section">
				<view class="section-title">粘贴旅客信息</view>
				<textarea class="input-area" v-model="pasteContent" placeholder="请粘贴包含旅客信息的文本内容，支持批量数据\n示例格式：\n姓名：张三\n电话：13800138000\n身份证：110101199001011234\n地址：北京市朝阳区\n\n姓名：李四\n电话：13900139000\n身份证：310101199001012345\n地址：上海市浦东新区" auto-height
			:disabled="isParsing"></textarea>

				<view class="button-group">
					<button class="parse-btn" :disabled="!pasteContent || isParsing" @click="parseContent">
						{{ isParsing ? '解析中...' : '解析识别' }}
					</button>
					<button class="reset-btn" :disabled="isParsing" @click="resetForm">
						重置清空
					</button>
				</view>
			</view>

			<!-- 加载动画 -->
			<view v-if="isParsing" class="loading-section">
				<view class="loading-animation">
					<view class="loading-spinner"></view>
					<view class="loading-text">正在智能解析，请稍候...</view>
				</view>
			</view>

			<!-- 解析结果区域 -->
			<view v-if="parsedResults.length > 0 && !isParsing" class="results-section">
				<view class="section-title">解析结果（{{ parsedResults.length }}条）</view>

				<view class="save-btn-container">
					<button class="save-all-btn" @click="saveAllTravelers" :disabled="parsedResults.length === 0">
						批量保存（{{ parsedResults.length }}人）
					</button>
				</view>

				<view class="results-list">
					<view v-for="(traveler, index) in parsedResults" :key="index" class="traveler-item">
						<view class="item-header">
							<view class="traveler-index">旅客 {{ index + 1 }}</view>
						</view>

						<view class="traveler-form">
							<view class="form-item">
								<text class="label">姓名：</text>
								<input v-model="traveler.name" class="input" placeholder="姓名" />
							</view>

							<view class="form-item">
								<text class="label">手机号：</text>
								<input v-model="traveler.phone" class="input" placeholder="手机号" type="number" />
							</view>

							<view class="form-item">
								<text class="label">身份证号：</text>
								<input v-model="traveler.idCard" class="input" placeholder="身份证号" />
							</view>

							<view class="form-item">
								<text class="label">地址：</text>
								<input v-model="traveler.address" class="input" placeholder="地址" />
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 无结果提示 -->
			<view v-if="showNoResults && !isParsing" class="no-results">
				<view class="empty-icon">📋</view>
				<text class="empty-text">暂无解析结果</text>
				<text class="empty-hint">请输入旅客信息后点击解析识别</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		smartParseTraveler,
		batchCreateTraveler
	} from '../../https/traveler.js';

	export default {
		data() {
			return {
				pasteContent: '',
				parsedResults: [],
				isParsing: false,
				showNoResults: true,
				groupId: '',
				selectedOrder: null,
				guestForm: {
					orderId: 0,
					orderNo: ''
				}
			};
		},

		onLoad(options) {
			const orderStr = options.order || '';
			const guestStr = options.guest || '';
			this.groupId = options.groupId || '';
			// 处理订单参数（如果有）
			if (orderStr) {
				try {
					const order = JSON.parse(decodeURIComponent(orderStr));
					this.selectedOrder = order;
					this.guestForm.orderId = order.id;
					this.guestForm.orderNo = order.orderNo;
				} catch (e) {
					console.error('解析订单数据失败:', e);
				}
			}
		},

		methods: {
			// 解析内容
			async parseContent() {
				if (!this.pasteContent.trim()) {
					uni.showToast({
						title: '请输入要解析的内容',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 清空之前的结果
				this.parsedResults = [];
				this.isParsing = true;
				this.showNoResults = false;

				try {
					// 显示加载动画
					this.showLoadingAnimation();

					// 添加解析开始的动画效果
					uni.showLoading({
						title: '智能解析中...',
						mask: true
					});

					// 调用智能解析API
					const res = await smartParseTraveler({
						pasteContent: this.pasteContent.trim()
					});

					// 隐藏加载提示
					uni.hideLoading();

					// 处理解析结果
					if (res) {
						// 格式化解析结果
						this.parsedResults = res.map(item => ({
							name: item.name || '',
							phone: item.phone || '',
							idCard: item.idCard || '',
							address: item.address || ''
						})).filter(item =>
							// 过滤掉无效数据（至少要有姓名或身份证号）
							item.name.trim() || item.idCard.trim()
						);

						if (this.parsedResults.length === 0) {
							this.showNoResults = true;
							uni.showToast({
								title: '未解析到有效旅客信息',
								icon: 'none',
								duration: 2000
							});
						} else {
							// 解析成功提示
							uni.showToast({
								title: `成功解析 ${this.parsedResults.length} 条信息`,
								icon: 'success',
								duration: 1500
							});

							// 添加结果出现的动画效果
							this.$nextTick(() => {
								this.addResultsAnimation();
							});
						}
					} else {
						this.showNoResults = true;
						uni.showToast({
							title: '解析失败，请检查输入内容格式',
							icon: 'none',
							duration: 2000
						});
					}
				} catch (error) {
					console.error('解析失败:', error);
					uni.hideLoading();
					this.showNoResults = false;

					// 直接清空结果，不使用模拟数据
					this.parsedResults = [];

					// 结果动画
					this.$nextTick(() => {
						this.addResultsAnimation();
					});
				} finally {
					this.isParsing = false;
					this.hideLoadingAnimation();
				}
			},

			// 已删除模拟数据方法

			// 为结果添加动画效果
			addResultsAnimation() {
				// 在uni-app中使用动画API替代直接DOM操作
				this.$nextTick(() => {
					// 可以通过数据绑定或CSS动画实现效果
					// 在样式中使用transition和初始状态
				});
			},

			// 重置表单
			resetForm() {
				this.pasteContent = '';
				this.parsedResults = [];
				this.showNoResults = true;
				// 保留订单信息，但清除解析数据和后台返回数据
				console.log('已重置解析数据和后台返回数据');

				// 显示重置成功提示
				uni.showToast({
					title: '已清除解析结果',
					icon: 'success',
					duration: 1500
				});
			},

			// 显示加载动画
			showLoadingAnimation() {
				// 在uni-app中不直接操作DOM，使用数据驱动或CSS动画
				this.$nextTick(() => {
					// 可以通过数据绑定或CSS动画实现效果
				});
			},

			// 隐藏加载动画
			hideLoadingAnimation() {
				// 在uni-app中不直接操作DOM，使用数据驱动或CSS动画
				this.$nextTick(() => {
					// 可以通过数据绑定或CSS动画实现效果
				});
			},

			// 批量保存旅客信息
			async saveAllTravelers() {
				if (this.parsedResults.length === 0) {
					uni.showToast({
						title: '没有可保存的旅客信息',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 验证必填字段
				const validResults = this.validateResults();
				if (validResults.invalidCount > 0) {
					uni.showModal({
						title: '提示',
						content: `有 ${validResults.invalidCount} 条信息缺少必填字段（姓名和身份证号），是否只保存有效信息？`,
						success: (res) => {
							if (res.confirm) {
								this.doBatchSaveTravelers(validResults.validList);
							}
						}
					});
					return;
				}

				// 所有信息都有效，直接保存
				this.doBatchSaveTravelers(this.parsedResults);
			},

			// 验证解析结果
			validateResults() {
				const validList = [];
				const invalidCount = 0;

				this.parsedResults.forEach((traveler, index) => {
					if (traveler.name && traveler.name.trim() && traveler.idCard && traveler.idCard.trim()) {
						validList.push({
							...traveler,
							index
						});
					}
				});

				return {
					validList,
					invalidCount: this.parsedResults.length - validList.length
				};
			},

			async doBatchSaveTravelers(travelersToSave) {
				// 显示加载提示
				uni.showLoading({
					title: '保存中...',
					mask: true
				});

				// 准备批量保存数据
				const list = travelersToSave.map(traveler => ({
					orderId: this.guestForm.orderId,
					groupId: this.groupId,
					name: traveler.name || '',
					phone: traveler.phone || '',
					orderNo: this.guestForm.orderNo || '',
					idCard: traveler.idCard || '',
				}));

				try {
					// 调用批量创建接口
					const res = await batchCreateTraveler({
						list
					});

					// 隐藏加载提示
					uni.hideLoading();

					// 处理保存结果
					if (res) {
						// 保存成功
						uni.showToast({
							title: `成功保存全部 ${travelersToSave.length} 位旅客信息`,
							icon: 'success',
							duration: 2000
						});

						// 添加保存成功的动画效果
						this.showSaveSuccessAnimation();

						// 延迟后清空表单并返回
						setTimeout(() => {
							this.resetForm();
							uni.navigateBack();
						}, 1500);
					} else {
						// 保存失败
						uni.showModal({
							title: '保存失败',
							content: res ? (res.message || '保存失败，请重试') : '服务器未返回响应',
							showCancel: false
						});
					}
				} catch (error) {

					// 保存失败
					uni.showModal({
						title: '保存失败',
						content: res ? (res.message || '保存失败，请重试') : '服务器未返回响应',
						showCancel: false
					});
				}
			},

			// 显示保存成功动画
			showSaveSuccessAnimation() {
				// 在uni-app中使用数据驱动方式实现动画
				// 可以通过添加一个状态变量来控制按钮样式和内容
				// 由于直接DOM操作不可用，我们依赖CSS动画和数据绑定
				console.log('保存成功动画触发');
			}
		}
	};
</script>

<style scoped>
	/* 全局样式 */
	.smart-parse-container {
		min-height: 100vh;
		background: linear-gradient(180deg, #f0f8ff 0%, #e1f5fe 100%);
		position: relative;
		overflow: hidden;
	}

	/* 装饰元素 - 增强旅游行业风格 */
	.smart-parse-container::before {
		content: '';
		position: absolute;
		top: 20%;
		right: -200rpx;
		width: 500rpx;
		height: 500rpx;
		background: rgba(33, 150, 243, 0.05);
		border-radius: 50%;
		z-index: 0;
	}

	.smart-parse-container::after {
		content: '';
		position: absolute;
		bottom: 20%;
		left: -200rpx;
		width: 600rpx;
		height: 600rpx;
		background: rgba(33, 150, 243, 0.03);
		border-radius: 50%;
		z-index: 0;
	}

	/* 头部样式 */
	.header {
		background: linear-gradient(135deg, #1976d2 0%, #2196f3 100%);
		padding: 44rpx 30rpx 50rpx;
		position: relative;
		box-shadow: 0 4rpx 20rpx rgba(25, 118, 210, 0.3);
		overflow: hidden;
	}

	.header::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="water" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M0 10 Q 5 0, 10 10 Q 15 20, 20 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5" /></pattern></defs><rect width="100" height="100" fill="url(%23water)" /></svg>');
		opacity: 0.3;
	}

	.title {
		font-size: 44rpx;
		font-weight: bold;
		color: #ffffff;
		text-align: center;
		position: relative;
		z-index: 1;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
	}

	/* 主要内容 */
	.content {
		padding: 30rpx;
		position: relative;
		z-index: 1;
	}

	.section-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #0d47a1;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.section-title::before {
		content: '';
		display: inline-block;
		width: 10rpx;
		height: 34rpx;
		background: linear-gradient(135deg, #1976d2 0%, #2196f3 100%);
		border-radius: 5rpx;
		margin-right: 15rpx;
	}

	/* 订单信息区域 */
	.order-info-section {
		background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
		border-radius: 20rpx;
		padding: 24rpx 30rpx;
		margin-bottom: 24rpx;
		border: 1rpx solid rgba(33, 150, 243, 0.2);
	}

	.order-info {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.order-label {
		font-size: 28rpx;
		color: #0d47a1;
		font-weight: 500;
		margin-right: 10rpx;
	}

	.order-no {
		font-size: 30rpx;
		color: #0d47a1;
		font-weight: bold;
		word-break: break-all;
		text-align: center;
	}

	/* 输入区域 */
	.input-section {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
		margin-bottom: 30rpx;
		border: 1rpx solid rgba(33, 150, 243, 0.1);
		position: relative;
		overflow: hidden;
	}

	.input-section::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 4rpx;
		background: linear-gradient(90deg, #1976d2 0%, #2196f3 100%);
	}

	.input-area {
			width: 100%;
			min-height: 220rpx;
			background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
			border: 2rpx solid #e3f2fd;
			border-radius: 16rpx;
			padding: 24rpx;
			font-size: 28rpx;
			color: #333;
			margin-bottom: 24rpx;
			transition: all 0.3s ease;
			box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
			white-space: pre-wrap;
			word-wrap: break-word;
		}
		
		.input-area::-webkit-input-placeholder {
			white-space: pre-wrap;
			word-wrap: break-word;
		}
		
		.input-area:-moz-placeholder {
			white-space: pre-wrap;
			word-wrap: break-word;
		}
		
		.input-area::-moz-placeholder {
			white-space: pre-wrap;
			word-wrap: break-word;
		}
		
		.input-area:-ms-input-placeholder {
			white-space: pre-wrap;
			word-wrap: break-word;
		}

	.input-area:focus {
		border-color: #2196f3;
		box-shadow: inset 0 2rpx 6rpx rgba(33, 150, 243, 0.1);
	}

	/* 按钮组 */
	.button-group {
		display: flex;
		gap: 24rpx;
	}

	.parse-btn,
	.reset-btn,
	.save-all-btn {
		flex: 1;
		padding: 10rpx 0;
		font-size: 23rpx;
		border-radius: 12rpx;
		border: none;
		outline: none;
		font-weight: 500;
		transition: all 0.3s ease;
		position: relative;
		overflow: hidden;
	}

	.parse-btn {
		background: linear-gradient(135deg, #1976d2 0%, #2196f3 100%);
		color: #ffffff;
		box-shadow: 0 6rpx 16rpx rgba(25, 118, 210, 0.3);
	}

	.parse-btn:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 10rpx rgba(25, 118, 210, 0.2);
	}

	.parse-btn[disabled] {
		background: #cccccc;
		box-shadow: none;
	}

	.reset-btn {
		background: linear-gradient(180deg, #fafafa 0%, #f5f5f5 100%);
		color: #666666;
		border: 2rpx solid #e0e0e0;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.reset-btn:active {
		transform: scale(0.98);
		background: #f0f0f0;
	}

	.reset-btn[disabled] {
		background: #f5f5f5;
		color: #cccccc;
		border-color: #eeeeee;
	}

	/* 保存成功动画 */
	.save-success-animation {
		animation: saveSuccess 1.5s ease-in-out;
	}

	@keyframes saveSuccess {
		0% {
			transform: scale(1);
			box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.3);
		}

		50% {
			transform: scale(1.1);
			box-shadow: 0 8rpx 20rpx rgba(76, 175, 80, 0.5);
			background: #4caf50 !important;
		}

		100% {
			transform: scale(1);
			box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
			background: #4caf50 !important;
		}
	}

	/* 加载动画 */
	.loading-section {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 80rpx 0;
	}

	.loading-animation {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
	}

	.loading-spinner {
		width: 70rpx;
		height: 70rpx;
		border: 8rpx solid rgba(33, 150, 243, 0.1);
		border-top: 8rpx solid #2196f3;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 24rpx;
		position: relative;
	}

	.loading-spinner::after {
		content: '';
		position: absolute;
		top: -16rpx;
		left: -16rpx;
		right: -16rpx;
		bottom: -16rpx;
		border: 2rpx dashed rgba(33, 150, 243, 0.3);
		border-radius: 50%;
		animation: spin 4s linear infinite reverse;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 30rpx;
		color: #0d47a1;
		font-weight: 500;
	}

	/* 结果区域 */
	.results-section {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
		border: 1rpx solid rgba(33, 150, 243, 0.1);
	}

	.save-btn-container {
		margin-bottom: 30rpx;
		animation: fadeIn 0.5s ease;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.save-all-btn {
		background: linear-gradient(135deg, #4caf50 0%, #66bb6a 100%);
		color: #ffffff;
		box-shadow: 0 6rpx 16rpx rgba(76, 175, 80, 0.3);
		font-weight: bold;
	}

	.save-all-btn:active {
		transform: scale(0.98);
		box-shadow: 0 4rpx 10rpx rgba(76, 175, 80, 0.2);
	}

	.results-list {
		max-height: 600rpx;
		overflow-y: auto;
		padding-right: 10rpx;
	}

	/* 滚动条样式 */
	.results-list::-webkit-scrollbar {
		width: 8rpx;
	}

	.results-list::-webkit-scrollbar-track {
		background: #f1f1f1;
		border-radius: 4rpx;
	}

	.results-list::-webkit-scrollbar-thumb {
		background: linear-gradient(180deg, #1976d2 0%, #2196f3 100%);
		border-radius: 4rpx;
	}

	/* 旅客信息项 */
	.traveler-item {
		border: 2rpx solid #e3f2fd;
		border-radius: 16rpx;
		padding: 28rpx;
		margin-bottom: 24rpx;
		background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
		transition: all 0.3s ease;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.traveler-item:hover {
		border-color: #2196f3;
		box-shadow: 0 6rpx 16rpx rgba(33, 150, 243, 0.1);
		transform: translateY(-2rpx);
	}

	.traveler-item:last-child {
		margin-bottom: 0;
	}

	.item-header {
		margin-bottom: 24rpx;
		padding-bottom: 16rpx;
		border-bottom: 2rpx solid #e3f2fd;
	}

	.traveler-index {
		font-size: 30rpx;
		font-weight: bold;
		color: #0d47a1;
		background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
		padding: 8rpx 20rpx;
		border-radius: 50rpx;
		display: inline-block;
	}

	.traveler-form {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 8rpx 0;
	}

	.label {
		font-size: 28rpx;
		color: #0d47a1;
		width: 160rpx;
		flex-shrink: 0;
		font-weight: 500;
	}

	.input {
		flex: 1;
		font-size: 28rpx;
		color: #333333;
		border: 2rpx solid #e3f2fd;
		border-radius: 10rpx;
		padding: 16rpx;
		background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
		transition: all 0.3s ease;
		box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
	}

	.input:focus {
		border-color: #2196f3;
		box-shadow: inset 0 2rpx 6rpx rgba(33, 150, 243, 0.1);
	}

	/* 无结果提示 */
	.no-results {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		background: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
		border: 1rpx dashed #e3f2fd;
	}

	.empty-icon {
		font-size: 120rpx;
		margin-bottom: 30rpx;
		animation: float 3s ease-in-out infinite;
	}

	@keyframes float {
		0% {
			transform: translateY(0);
		}

		50% {
			transform: translateY(-20rpx);
		}

		100% {
			transform: translateY(0);
		}
	}

	.empty-text {
		font-size: 34rpx;
		color: #0d47a1;
		margin-bottom: 15rpx;
		font-weight: 500;
	}

	.empty-hint {
		font-size: 28rpx;
		color: #78909c;
		text-align: center;
		padding: 0 60rpx;
		line-height: 1.6;
	}

	/* 响应式优化 */
	@media screen and (min-width: 768px) {
		.content {
			max-width: 700rpx;
			margin: 0 auto;
		}
	}
</style>